package com.iplus.ydkf.ehome.module;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.avos.avoscloud.AVUser;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.iplus.ydkf.ehome.R;
import com.iplus.ydkf.ehome.common.net.Callback;
import com.iplus.ydkf.ehome.common.net.JsonParser;
import com.iplus.ydkf.ehome.common.net.JsonRequestBody;
import com.iplus.ydkf.ehome.common.net.NetClient;
import com.iplus.ydkf.ehome.config.ConString;
import com.iplus.ydkf.ehome.module.base.BaseActivity;
import com.iplus.ydkf.ehome.module.base.BaseFragment;
import com.iplus.ydkf.ehome.module.device.DeviceFragment;
import com.iplus.ydkf.ehome.module.home.IndexFragment;
import com.iplus.ydkf.ehome.module.login.LoginActivity;
import com.iplus.ydkf.ehome.module.video.VideoFragment;

import java.io.IOException;
import java.util.Locale;

import butterknife.Bind;
import okhttp3.RequestBody;


public class MainActivity extends BaseActivity {
    @Bind(R.id.viewpager)
    ViewPager viewPager;
    @Bind(R.id.tabs)
    TabLayout tabLayout;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.fab)
    FloatingActionButton fab;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.navigation_view)
    NavigationView navigationView;
    private BaseFragment[] fragments = {IndexFragment.getInstance(), DeviceFragment.getInstance(), VideoFragment.getInstance()};
    private PageAdapter pageAdapter;

    @Override
    public int bindLayout() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(View view) {
        setSupportActionBar(toolbar);
        pageAdapter = new PageAdapter(getSupportFragmentManager());
        viewPager.setAdapter(pageAdapter);
        tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
        tabLayout.setSelectedTabIndicatorHeight(10);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        toolbar.setNavigationIcon(R.drawable.icon_menu);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                if (item.getItemId() == R.id.menu_logout) {
                    AVUser.logOut();
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    finish();
                }
                return false;
            }
        });
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                App.getCurrentUser().logOut();
//                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                showDialog();
            }
        });
        getSupportActionBar().setTitle("E居");
    }

    private void showDialog() {
//        1. 创建RecognizerDialog对象
        RecognizerDialog mDialog = new RecognizerDialog(this, new InitListener() {
            @Override
            public void onInit(int i) {
                if (i != ErrorCode.SUCCESS)
                    snackbar("初始化错误");
            }
        });
        //2.设置accent、language等参数
        mDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        mDialog.setParameter(SpeechConstant.ACCENT, "mandarin");
        mDialog.setUILanguage(Locale.CHINA);
        //若要将UI控件用于语义理解，必须添加以下参数设置，设置之后onResult回调返回将是语义理解结果
//        mDialog.setParameter("asr_sch", "1");
//        mDialog.setParameter("nlp_version", "2.0");
        //3.设置回调接口
        mDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                JSONObject jsonObject = JSON.parseObject(recognizerResult.getResultString());
                if (jsonObject.getIntValue("sn") == 1)
                    check(jsonObject.getJSONArray("ws"));
            }

            @Override
            public void onError(SpeechError speechError) {
                snackbar("识别错误");
            }
        });
        //4.显示dialog，接收语音输入
        mDialog.show();
    }

    private void check(JSONArray ws) {
        String device_id = null;
        String commandname = null;
        String roomname = null;
        boolean query = false;
        int state = -1;
        for (int i = 0; i < ws.size(); i++) {
            String w = ws.getJSONObject(i).getJSONArray("cw").getJSONObject(0).getString("w");
            switch (w) {
                case "打开":
                case "开启":
                case "开":
                    state = 1;
                    break;
                case "关闭":
                case "关掉":
                case "关":
                case "停":
                    state = 0;
                    break;
                case "卧室":
                    roomname = "卧室";
                    device_id = "1100075";
                    break;
                case "客厅":
                    roomname = "客厅";
                    device_id = "1100075";
                    break;
                case "厨房":
                    device_id = "3059568";
                    roomname = "厨房";
                    break;
                case "蜂鸣器":
                    commandname = "2";
                    break;
                case "排气扇":
                    commandname = "3";
                    break;
                case "灯光":
                case "灯":
                case "光":
                    commandname = "7";
                    break;
                case "温度":
                    commandname = "temperature";
                    break;
                case "湿度":
                    commandname = "humidity";
                    break;
                case "有人":
                    commandname = "humanbody";
                    break;
                case "亮度":
                case "光线强度":
                    commandname = "light";
                    break;
                case "告诉":
                case "查一查":
                case "知道":
                case "多少":
                case "吗":
                    query = true;

            }
        }
        if (query) {
            if (roomname == null || device_id == null || commandname == null) {
                snackbar("识别命令错误！");
                return;
            }
            getQuery(roomname, device_id, commandname);
            return;
        }
        if (state == -1 || commandname == null || device_id == null) {
            snackbar("识别命令错误！");
            return;
        }
        String url = ConString.CLOUD_DEVICE + "/" + device_id + "/" + commandname + "/" + state;
        RequestBody jsonRequestBody = JsonRequestBody.create().put("123", "1q23").build();
        loge(url);
        NetClient.sendPostRequest(url, jsonRequestBody, new Callback<JSONObject>(JsonParser.getInstance()) {
            @Override
            public void onResponse(JSONObject jsonObject) {
                if (jsonObject.getIntValue("errorCode") != 0) {
                    snackbar(jsonObject.getString("errorMsg"));
                    return;
                } else snackbar("操作成功");
            }

            @Override
            public void onFailure(IOException e) {

            }
        });
    }

    @Override
    public void initData(View view) {
    }

    @Override
    public String getFragmentName() {
        return null;
    }

    public void getQuery(final String roomname, String device_id, final String commandname) {
        NetClient.sendGetRequest(ConString.CLOUD_DEVICE + "/" + device_id + "/" + commandname, new Callback<JSONObject>
                        (JsonParser
                                .getInstance()) {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        if (jsonObject.getIntValue("errorCode") == 0) {
                            int state = jsonObject.getJSONArray("data").getJSONObject(0).getIntValue("online");
                            float currentValue = Float.valueOf(jsonObject.getJSONArray("data").getJSONObject(0)
                                    .getString
                                            ("current_value"));
                            String s = getTips(roomname, commandname, state, currentValue);
                            SpeechSynthesizer mTts = SpeechSynthesizer.createSynthesizer(MainActivity.this, null);
                            mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan");//设置发音人
                            mTts.setParameter(SpeechConstant.SPEED, "50");//设置语速
                            mTts.setParameter(SpeechConstant.VOLUME, "80");//设置音量，范围0~100
                            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); //设置云端
                            mTts.startSpeaking(s, mSynListener);
                        }
                    }

                    @Override
                    public void onFailure(IOException e) {

                    }
                }

        );

    }

    private String getTips(String roomname, String commandname, int state, float currentValue) {
        StringBuilder sb = new StringBuilder();
        switch (commandname) {
            case "humanbody":
                sb.append(roomname + (currentValue == 0 ? "当前没有人" : "当前有人"));
                break;
            case "humidity":
                sb.append(roomname + "当前的湿度是" + currentValue);
                break;
            case "light":
                sb.append(roomname + "当前的亮度是" + currentValue + "流明");
                break;
            case "temperature":
                sb.append(roomname + "当前的温度是" + currentValue + "摄氏度");
                break;
        }
        sb.append("," + (state == 0 ? "设备已离线" : ""));
        return sb.toString();
    }

    private SynthesizerListener mSynListener = new SynthesizerListener() {
        public void onCompleted(SpeechError error) {
        }

        public void onBufferProgress(int percent, int beginPos, int endPos, String info) {
        }

        public void onSpeakBegin() {
        }

        public void onSpeakPaused() {
        }

        public void onSpeakProgress(int percent, int beginPos, int endPos) {
        }

        public void onSpeakResumed() {
        }

        public void onEvent(int arg0, int arg1, int arg2, Bundle arg3) {
        }
    };

    private class PageAdapter extends FragmentStatePagerAdapter {

        public PageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments[position];
        }

        @Override
        public int getCount() {
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return fragments[position].getFragmentName();
        }
    }

}
